<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * RMB相关接口
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Phil Sturgeon, Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Cny extends REST_Controller {
    private $user_info;
    function __construct()
    {
        parent::__construct();
        //加载通行证类
        $this->load->library('passPort');
        $this->passportClass = $this->passport;

        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
        $this->user_info = $this->passportClass->checkCookieAuthCode('','',true);
        if(empty($this->user_info)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 200001,
                $this->config->item('rest_message_field_name') => '请先登陆'
            ), REST_Controller::HTTP_OK);
        }
    }

    /**
     * 充值操作
     */
    public function deposit_post()
    {
        $this->load->config('cny');
        $cnySTOP = $this->config->item('cnySTOP');
        if($cnySTOP==1){
            $this->alertMsg('暂未开放');
        }

        $post = $this->post();
        $amount = $post['amount'];
        $this->load->config('gopay_config');
        $url = $this->config->item('url');
        $version = $this->config->item('version');
        $charset = $this->config->item('charset');
        $language = $this->config->item('language');
        $signType = $this->config->item('signType');
        $tranCode = $this->config->item('tranCode');
        $merchantID = $this->config->item('merchantID');
        //注意调试生产环境时需要修改这个值为生产参数
        $datetime = date('Y-m-d H:i:s');
        $tranIP = get_ip();//用户浏览器IP

        $amount = trim($post['amount']);
        if($amount<20){
            $this->alertMsg('充值金额不能少于20元');
        }

        $this->load->library('Order');
        $orderData = array(
            'recharge_type' => 2,//1微信，2gopay
            'uid' => $this->user_info['uid'],
            'openid' => $this->user_info['openid'],
            'amount' => $amount,
            'ip' => $tranIP,
            'create_time' => $datetime,
            'lastest_modify' => $datetime,
        );
        $out_trade_no = $this->order->createOrder($orderData,'gopay');
        if(!$out_trade_no){
            $this->alertMsg('充值提交失败');
        }
        $merOrderNum = $out_trade_no;//订单号
        $tranAmt = $amount;//交易金额
        $feeAmt = '0.00';//商户提取佣金金额
        $currencyType = $this->config->item('currencyType');
        $frontMerUrl = $this->config->item('frontMerUrl');
        $backgroundMerUrl = $this->config->item('backgroundMerUrl');
        $tranDateTime = date('YmdHis');//交易时间
        $virCardNoIn = $this->config->item('virCardNoIn');
        //注意调试生产环境时需要修改这个值为生产参数
        $isRepeatSubmit = $this->config->item('isRepeatSubmit');;//订单是否允许重复提交0:不允许,1:允许 (不填则当成1处理)
        $goodsName = 'product';//商品名称
        $goodsDetail = 'productDesc';//商品详情
        $buyerName = $this->config->item('buyerName');
        $buyerContact = '020-88888888';//买方联系方式
        $merRemark1 = '';//商户备用信息字段
        $merRemark2 = '';//商户备用信息字段
        $bankCode = '';//银行代码
        $userType = '';//用户类型
        $gopayServerTime = $this->getgopayServerTime();
        $VerficationCode = $this->config->item('VerficationCode');
        $signStr='version=['.$version.']tranCode=['.$tranCode.']merchantID=['.$merchantID.']merOrderNum=['.$merOrderNum.']tranAmt=['.$tranAmt.']feeAmt=['.$feeAmt.']tranDateTime=['.$tranDateTime.']frontMerUrl=['.$frontMerUrl.']backgroundMerUrl=['.$backgroundMerUrl.']orderId=[]gopayOutOrderId=[]tranIP=['.$tranIP.']respCode=[]gopayServerTime=['.$gopayServerTime.']VerficationCode=['.$VerficationCode.']';
        //VerficationCode是商户识别码为用户重要信息请妥善保存
        //注意调试生产环境时需要修改这个值为生产参数
        $signValue = md5($signStr);
echo <<<EOD
        <form method="post" action="{$url}">
        <input type="hidden" id="version" name="version" value="{$version}" size="50"/>
        <input type="hidden" id="charset" name="charset" value="{$charset}"  size="50"/>
        <input type="hidden" id="language" name="language" value="{$language}"  size="50"/>
        <input type="hidden" id="signType" name="signType" value="{$signType}"  size="50"/>
        <input type="hidden" id="tranCode" name="tranCode" value="{$tranCode}"  size="50"/>
        <input type="hidden" id="merchantID" name="merchantID" value="{$merchantID}"  size="50"/>
        <input type="hidden" id="merOrderNum" name="merOrderNum" value="{$merOrderNum}"  size="50" />
        <input type="hidden" id="tranAmt" name="tranAmt" value="{$tranAmt}"  size="50"/>
        <input type="hidden" id="feeAmt" name="feeAmt" value="{$feeAmt}"  size="50"/>
        <input type="hidden" id="currencyType" name="currencyType" value="{$currencyType}"  size="50"/>
        <input type="hidden"  id="frontMerUrl" name="frontMerUrl" value="{$frontMerUrl}"  size="50"/>
        <input type="hidden"  id="backgroundMerUrl" name="backgroundMerUrl" value="{$backgroundMerUrl}"  size="50"/>
        <input type="hidden"  id="tranDateTime" name="tranDateTime" value="{$tranDateTime}"  size="50"/>
        <input type="hidden"  id="virCardNoIn" name="virCardNoIn" value="{$virCardNoIn}"  size="50"/>
        <input type="hidden"  id="tranIP" name="tranIP" value="{$tranIP}"  size="50"/>
        <input type="hidden"  id="isRepeatSubmit" name="isRepeatSubmit" value="{$isRepeatSubmit}"  size="50"/>
        <input type="hidden"  id="goodsName" name="goodsName" value="{$goodsName}"  size="50"/>
        <input type="hidden"  id="goodsDetail" name="goodsDetail" value="{$goodsDetail}"  size="50"/>
        <input type="hidden"  id="buyerName" name="buyerName" value="{$buyerName}"  size="50"/>
        <input type="hidden"  id="buyerContact" name="buyerContact" value="{$buyerContact}"  size="50"/>
        <input type="hidden"  id="merRemark1" name="merRemark1" value="{$merRemark1}"  size="50"/>
        <input type="hidden"  id="merRemark2" name="merRemark2" value="{$merRemark2}"  size="50"/>
        <input type="hidden"  id="signValue" name="signValue" value="{$signValue}"  size="50"/>
        <input type="hidden"  id="bankCode" name="bankCode" value="{$bankCode}"  size="50"/>
        <input type="hidden"  id="userType" name="userType" value="{$userType}"  size="50"/>
        <input type="hidden"  id="gopayServerTime" name="gopayServerTime" value="{$gopayServerTime}"  size="50"/>
        </form>
        <script>
        document.forms[0].submit();
        </script>
EOD;
        die;
    }

	 /**
     * 提现操作
     */
    public function withdraw_post()
    {
        $this->load->config('cny');
        $cnySTOP = $this->config->item('cnySTOP');
        if($cnySTOP==1){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 99999,
                $this->config->item('rest_message_field_name') => '暂未开放'
            ), REST_Controller::HTTP_OK);
        }
        $post		= $this->post();
        $amount		= trim($post['amount']);
		$bank		= trim($post['bank']);
		$prov		= trim($post['prov']);
		$city		= trim($post['city']);
		$bank_name	= trim($post['bank_name']);
		$card_no	= trim($post['card_no']);
		$card_name	= trim($post['card_name']);
        writeDebug('['.date('Y-m-d H:i:s').'] uid '.$this->user_info['uid'].' post='.var_export($post,true),'withdraw');
		if(empty($amount)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '请输入提现金额'
            ), REST_Controller::HTTP_OK);
		}
        if($amount <=0 || !is_numeric($amount)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100012,
                $this->config->item('rest_message_field_name') => '提现金额错误'
            ), REST_Controller::HTTP_OK);
        }
        if($amount < 50){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100022,
                $this->config->item('rest_message_field_name') => '提现金额不能少于50元'
            ), REST_Controller::HTTP_OK);
        }
		if($amount >$this->user_info['cny']){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '账户余额不足'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($bank)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100003,
                $this->config->item('rest_message_field_name') => '请选择银行'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($prov)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100004,
                $this->config->item('rest_message_field_name') => '请选择省份'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($city)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100005,
                $this->config->item('rest_message_field_name') => '请选择城市'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($bank_name)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '请输入开户行支行名称'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($card_no)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100007,
                $this->config->item('rest_message_field_name') => '请输入银行卡号'
            ), REST_Controller::HTTP_OK);
		}
		if(empty($card_name)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100008,
                $this->config->item('rest_message_field_name') => '请输入持卡人姓名'
            ), REST_Controller::HTTP_OK);
		}
		$this->load->library('Bank');
		$uid		=	$this->user_info['uid'];
		$bank_arr	=	$this->bank->getBank($uid);
		if(empty($bank_arr)){
			$in_arr	=	array(
				'uid'	=>	$uid,
				'bank'	=>	$bank,
				'prov'	=>	$prov,
				'city'	=>	$city,
				'bank_name'	=>	$bank_name,
				'card_no'	=>	$card_no,
				'card_name'	=>	$card_name,
				'status'	=>	1,
				'datetime'	=>	date("Y-m-d H:i:s"),
			);
			$bank_id	=	$this->bank->saveBank($in_arr);
			if(empty($bank_id)){
                $this->response(array(
                    $this->config->item('rest_status_field_name') => 100009,
                    $this->config->item('rest_message_field_name') => '提现失败[100009]'
                ), REST_Controller::HTTP_OK);
			}
		}else{
			$bank_id	=	$bank_arr['id'];
		}
		$source = $this->config->item('bank_withdraw_source');
		$reduce_arr  =  array(
			'uid'=> $uid,
			'name' => 'ACCOUNT',//帐户
			'use_value' => $amount,
			'source' => $source,
			'add_time' => date("Y-m-d H:i:s"),
		);
		$this->load->library('Cny_Class');
		if(!$this->cny_class->reduce($reduce_arr)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100010,
                $this->config->item('rest_message_field_name') => '提现失败[100010]'
            ), REST_Controller::HTTP_OK);
		};
		$this->load->library('Order');
    $fee = 2;//提现手续费每笔2元
    if($amount<=200){//检查是否有免手续费资格
        // $where = array(
        //     'uid' => $uid,
        // );
        // $this->load->model('cny_model');
        // $cnyShare = $this->cny_model->getCnyShare($where,1);
        // $freeNum = isset($cnyShare['num'])?$cnyShare['num']:0;
        // if($freeNum>0){
        //     $fee = 0;
        //     $upArr = array(
        //         'num' => 0,
        //         'lastest_modify' => date("Y-m-d H:i:s"),
        //     );
        //     $this->cny_model->updateCnyShare($upArr,$where);
        // }
        $send_amount=   bcsub($amount,$fee,2);
    }else{
        $send_amount=   bcsub($amount,$fee,2);
    }
    sendSMS(86, 15231011799, $send_amount,'withdraw');

		$order		=	array(
			'uid'	=>	$uid,
			'openid'=>	$this->user_info['openid'],
			'bank_id'=>	$bank_id,
			'amount'=>	$amount,
			'fee'	=>	$fee,
			'send_amount'=>	$send_amount,
			'ip'		 =>	get_ip(),
			'create_time'=>	date("Y-m-d H:i:s"),
		);
		$orderno	=	$this->order->createOrder($order,'','cny_withdraw');
		if(empty($orderno)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100011,
                $this->config->item('rest_message_field_name') => '提现失败[100011]'
            ), REST_Controller::HTTP_OK);
		}
		$this->passportClass->flushUserCache($uid);
		$this->response(array($this->config->item('rest_status_field_name')=>0), REST_Controller::HTTP_OK);
    }

    private function alertMsg($msg){
		echo <<<EOD
            <script>
            myAlert('{$msg}');
            </script>
EOD;
            die;
    }

    private function getgopayServerTime(){
        $url = "https://gateway.gopay.com.cn/time.do";
        return curl_get($url);

    }
}
